<template>
  <div>
    <el-button :type="type" @click="handleDownloadFile">
      <i v-if="isShowIcon" :class="icon"></i>
      {{ text }}
    </el-button>
  </div>
</template>

<script>
/**
 * xlsx导出公共组件封装
 * 依赖element-ui 的Button组件
 */
import Export from '@/utils/xlsx-export'

export default {
  name: 'elExport',
  props: {
    // 按钮文字
    text: {
      type: String,
      default: '导出',
    },
    // 同 Element type属性
    type: {
      type: String,
      default: 'primary',
    },
    // 是否显示图标
    isShowIcon: {
      type: Boolean,
      default: true,
    },
    // 同 Element class="el-icon-download"
    icon: {
      type: String,
      default: 'el-icon-download',
    },
    // 文件名称
    fileName: {
      type: String,
      default: '导出文件',
    },
    // 文件类型
    fileType: {
      type: String,
      default: 'xlsx',
    },
    // 导出的数据
    dataList: {
      type: Array,
      default: () => [],
    },
    // 数据表头
    dataHead: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      loading: null,
    }
  },
  methods: {
    handleDownloadFile() {
      if (!this.dataList.length) {
        return this.$emit('exportJsonToExcel', { msg: '数据源为空！', res: false })
      }

      return new Promise((resolve, reject) => {
        try {
          let filterVal = []
          let header = []
          if (!!this.dataHead.length) {
            filterVal = this.dataHead.map((o) => o.key || 'key property not found')
            header = this.dataHead.map((o) => o.value || 'value property not found')
          } else {
            filterVal = Object.keys(this.dataList[0])
            header = filterVal
          }

          const data = Export.formatJson(filterVal, this.dataList)
          Export.exportJsonToExcel({
            header,
            data,
            filename: this.fileName,
            bookType: this.fileType,
          })
          resolve()
        } catch (error) {
          reject(error)
        }
      })
        .then(() => {
          return this.$emit('exportJsonToExcel', { res: true })
        })
        .catch(() => {
          return this.$emit('exportJsonToExcel', { msg: '导出失败！', res: false })
        })
    },
  },
}
</script>

<style lang="less" scoped></style>
